
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
#include <sys/sysinfo.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include "util.h"
#include "rs232.h"

pthread_mutex_t ext_mutex;
void Delay_ms(unsigned int MilliSecond)
{
    struct timeval time;
    time.tv_sec = MilliSecond / 1000;           //seconds
    time.tv_usec = (MilliSecond % 1000) * 1000; //microsecond
    select(0, NULL, NULL, NULL, &time);
}

#if EXT_COM_SUPPORT
const static char mode[] = {'8', 'N', '1', 0};

uint32_t EXT_INDEX = 0;
void com_ext_init(void)
{
    pthread_mutex_init(&ext_mutex, NULL);
    EXT_INDEX = RS232_GetPortnr(S_IR_USB_INDEX);
}
int com_ext_open(void)
{
    if (RS232_OpenComport(EXT_INDEX, EXT_BAUDRATE, mode, 0))
    {
        printf("Can not open comport\n");
        return -1;
    }
    return 0;
}
int com_ext_read(unsigned char *buf, int size)
{
    return RS232_PollComport(EXT_INDEX, buf, size);
}
int com_ext_send(const uint8_t *buffer, int length)
{
    int num = 0, ret = 0;
#if 0
        printf("SEND[");
        for (int i = 0; i < length; ++i)
        {
            printf("%02X ", buffer[i]);
        }
        printf("]\n");
#endif
    pthread_mutex_lock(&ext_mutex);
    num = RS232_SendBuf(EXT_INDEX, (unsigned char *)buffer, length);
    if (num != length)
    {
        printf("----- Com Send Error %u:%u -----\n", length, num);
        ret = -1;
    }
    pthread_mutex_unlock(&ext_mutex);
    return ret;
}
#endif
int IsInt(char *str)
{
    int len;
    len = strlen(str);
    int i = 0;
    for (i; i < len; i++)
    {
        if (!(isdigit(str[i])))
            return 0;
    }
    return 1;
}
//1:exist 0:not exist
int is_file_exist(const char *file_path)
{
    if (file_path == NULL)
        return 0;
    if (access(file_path, F_OK) != 0)
        return 0;
    return 1;
}